package cn.com.yusys.yusp.admin.web.rest;

import cn.com.yusys.yusp.admin.domain.AdminSmLog;
import cn.com.yusys.yusp.admin.domain.AdminSmLogPojo;
import cn.com.yusys.yusp.admin.log.common.CommonLogInfo;
import cn.com.yusys.yusp.admin.log.common.DispatchLogService;
import cn.com.yusys.yusp.admin.service.SystemLogService;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.service.CommonService;
import cn.com.yusys.yusp.commons.util.CommonUtil;
import cn.com.yusys.yusp.commons.util.DateUtil;
import cn.com.yusys.yusp.commons.util.NumberUtil;
import cn.com.yusys.yusp.commons.util.StringUtil;
import cn.com.yusys.yusp.commons.web.rest.CommonResource;
import cn.com.yusys.yusp.commons.web.rest.IoResourceFactory;
import cn.com.yusys.yusp.commons.web.rest.dto.ResultDto;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @version 1.0.0
 * @项目名称: yusp-admin
 * @类名称: SystemLogResource
 * @类描述: 系统日志的导出, 删除, 和查询
 * @功能描述:
 * @创建人: lupan@yusys.com.cn
 * @创建时间: 2017-12-27 18:47
 * @修改备注:
 * @修改记录: 修改时间    修改人员    修改原因
 * -------------------------------------------------------------
 * @Copyright (c) 2017宇信科技-版权所有
 */
@RestController
@RequestMapping("/api/monitor")
public class SystemLogResource extends CommonResource<AdminSmLog, String> {

    @Autowired
    private SystemLogService logService;

    @Autowired
    private DispatchLogService dispatchLogService;

    @Autowired
    private IoResourceFactory factory;

    private String exportSql = "getLogByParam";
    private String pojoClassName = AdminSmLogPojo.class.getName();
    

    /**
     * @方法名称: getLog
     * @方法描述: 根据参数获取日志信息-logType:日志类型,userId:操作用户,operObjId:操作对象,beginTime-endTime操作时间从-到
     * @参数与返回说明:
     * @算法描述:
     */
    @GetMapping("/auditlogdata")
    public ResultDto<List<Map<String, Object>>> getLog(QueryModel model) {
        PageHelper.startPage(model.getPage(), model.getSize());
        if (model != null && model.getCondition() != null) {
            String endTime = StringUtil.replaceNullByObj(model.getCondition().get("endTime"));
            if (StringUtil.isNotEmpty(endTime)) {
                Date date = DateUtil.parseDate(endTime, DateUtil.PATTERN_DEFAULT);
                model.getCondition().put("endTime", DateUtil.formatDate(DateUtil.addDay(date, 1), DateUtil.PATTERN_DEFAULT));
            }
        }
        List<Map<String, Object>> list = logService.getLogByParam(model);
        PageHelper.clearPage();
        return new ResultDto<List<Map<String, Object>>>(list);
    }

    /**
     * 异步日志
     *
     * @param adminSmLog
     * @param request
     * @return
     */
    @PostMapping("/auditlogdata")
    public ResultDto<String> addLog(@RequestBody AdminSmLog adminSmLog, HttpServletRequest request) {
        ResultDto<String> resultDto = new ResultDto<>();
        if (adminSmLog != null) {
            if (StringUtil.isEmpty(adminSmLog.getLoginIp())) {
                adminSmLog.setLoginIp(getIpAddress(request));
            }
            if (StringUtil.isEmpty(adminSmLog.getOperTime())) {
                adminSmLog.setOperTime(DateUtil.formatDateTimeByDef());
            } else {
                adminSmLog.setOperTime(DateUtil.formatDateByDef(new Date(NumberUtil.toBigDecimal(adminSmLog.getOperTime()).longValue())));
            }
        }
        CommonLogInfo commonLogInfo = new CommonLogInfo();
        commonLogInfo.setLogInfo(adminSmLog);
        dispatchLogService.handleLog(commonLogInfo);
        resultDto.setData("Success");
        resultDto.setMessage("记录操作到日志中！");
        return resultDto;
    }

    protected CommonService getCommonService() {
        return logService;
    }

    public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    @GetMapping("/auditlogdata/export")
    public void export(QueryModel queryModel, HttpServletRequest request, HttpServletResponse response) throws IOException {
        factory.export(queryModel, request, response, exportSql, pojoClassName);
    }

    @GetMapping("/exportasync")
    public String asyncExport(QueryModel queryModel, Integer fetchSize) {
        return factory.asyncExport(queryModel, fetchSize, exportSql, pojoClassName);
    }

    @PostMapping("/auditlogdata/batchdelete")
    protected ResultDto<Integer> deletes(@RequestBody List<AdminSmLog> logs) {
        int result = 0;
        if (CommonUtil.nonNullOrEmpty(logs)) {
            List<String> ids = logs.parallelStream().map(AdminSmLog::getLogId).collect(Collectors.toList());
            result = getCommonService().deleteByIds(StringUtil.concat(ids, ","));
        }
        return new ResultDto<Integer>(result);
    }

}
